package cn.smile.business.msg.impl;

import cn.smile.bean.dto.msg.MsgConDTO;
import cn.smile.bean.entity.msg.EmailTemplate;
import cn.smile.business.msg.IEmailTempService;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.commons.enums.msg.MailCodeEnum;
import cn.smile.commons.exceptions.BusinessException;
import cn.smile.commons.response.MyResponseCode;
import cn.smile.repository.msg.EmailTemplateMapper;
import cn.smile.utils.EntityUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * @author smile-jt
 */
@Slf4j
@Service
public class EmailTempServiceImpl extends BaseServiceImpl<EmailTemplateMapper, EmailTemplate> implements IEmailTempService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgConDTO getMailCon(MailCodeEnum codeEnum, Object entity) {
        log.info("[EmailTempServiceImpl].[getMailCon] ------> Get Mail Content Start, codeEnum = {}, entity = {}", codeEnum, JSON.toJSONString(entity));
        MsgConDTO dto = new MsgConDTO();
        EmailTemplate template = baseMapper.selectOne(new QueryWrapper<EmailTemplate>().lambda().eq(EmailTemplate::getTemplateCode, codeEnum.getSn()).eq(EmailTemplate::getDeleted, Boolean.FALSE));
        dto.setMsgTitle(template.getMsgTitle());
        EvaluationContext context = EntityUtil.objectToContext(entity);
        ExpressionParser parser = new SpelExpressionParser();
        Object content = parser.parseExpression(template.getTemplateContent(), new TemplateParserContext()).getValue(context);
        if (ObjectUtils.isEmpty(content)) {
            throw new BusinessException(MyResponseCode.NULL_MAIL_CONTENT);
        }
        dto.setMsgContent(content.toString());
        log.info("[EmailTempServiceImpl].[getMailCon] ------> Get Mail Content End, dto = {}", JSON.toJSONString(dto));
        return dto;
    }
}
